package com.lenovo.agricultureclient.ui.activity;

import com.lenovo.agricultureclient.ClientApp;
import com.lenovo.agricultureclient.R;
import com.lenovo.agricultureclient.request.BaseRequest;
import com.lenovo.agricultureclient.request.GetConfigRequest;
import com.lenovo.agricultureclient.request.BaseRequest.RequestResult;
import com.lenovo.agricultureclient.ui.fragment.ControlFragment;
import com.lenovo.agricultureclient.ui.fragment.EnvirFragment;
import com.lenovo.agricultureclient.ui.fragment.HistoryFragment;
import com.lenovo.agricultureclient.ui.fragment.SettingFragment;
import com.lenovo.agricultureclient.util.DummyTabContent;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
/**
 * 本项目的主界面，主要由4个tab子窗体够成，分别是环境指标、历史数据查询、手动控制和系统设置四个子窗体
 * @author zongbingwu
 *
 */
public class MainActivity extends AppBaseActivity 
{
	public static final String TAG = "<MainActivity>";
	
	//4个tab子窗体的ID号
	private static final int ENVIR_FRAG = 0x00;
	private static final int HISTORY_FRAG = 0x01;
	private static final int CONTROL_FRAG = 0x02;
	private static final int SETTING_FRAG = 0x03;
	
	//tab host控件
	private TabHost mTabHost;
	//子窗体管理器
	private FragmentTransaction mft;
	
	private EnvirFragment mEnvirFragment;//环境指标子窗体
	private HistoryFragment mHistoryFragment;//历史数据查询子窗体
	private ControlFragment mControlFragment;//手动控制子窗体
	private SettingFragment mSettingFragment;//系统设置子窗体
	
	//4个子窗体对应的tab view
	RelativeLayout mEnvirTab,mHistorytab, mControlTab, mSettingTab;
	//默认要显示的子窗体
	private int mCurrentTab = ENVIR_FRAG;
	//标题
	private TextView mTitleTextView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.main_activity);
		initView();
		//先从服务器端获取所有传感器的阀值
		getSensorConfigFromNet();
		//开启线程，开始不断的获取传感器数据
		startGetSensorData();
    }
    
    //从服务器端获取所有传感器的阀值
	private void getSensorConfigFromNet()
	{
		GetConfigRequest getConfigRequest = new GetConfigRequest();
		getConfigRequest.setSensorConfig(mApp.getSensorConfig());
		getConfigRequest.setOnResponseEventListener(new BaseRequest.OnResponseEventListener() {
			@Override
			public void onResponse(BaseRequest request, RequestResult result) {
				//处理请求结果
				GetConfigRequest getConfigRequest = (GetConfigRequest)request;
				if(getConfigRequest!=null && getConfigRequest.isSuccess())
				{
					mApp.saveSensorConfig();//保存所有传感器预警值的范围
					onGetSensor();//获取到传感器数据以后，刷新环境指标子窗体界面
				}
			}
		});
		//开始线程
		startRequest(getConfigRequest);
	}
	
	private void initView()
	{
		mTitleTextView = (TextView)findViewById(R.id.title_text_view);
		mTitleTextView.setText(R.string.envir_target);
		
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		createTabView();
        mTabHost.setup();
        
        TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener(){
			@Override
			public void onTabChanged(String tabId) {
				/**碎片管理*/
				FragmentManager fm =  getFragmentManager();
				//根据名称找到相应的子窗体
				mEnvirFragment = (EnvirFragment) fm.findFragmentByTag(EnvirFragment.TAG);
				mHistoryFragment = (HistoryFragment) fm.findFragmentByTag(HistoryFragment.TAG);
				mControlFragment = (ControlFragment) fm.findFragmentByTag(ControlFragment.TAG);
				mSettingFragment = (SettingFragment) fm.findFragmentByTag(SettingFragment.TAG);
				mft = fm.beginTransaction();
				
				//先分离这些子窗体
				if(mEnvirFragment!=null)
					mft.detach(mEnvirFragment);
				if(mHistoryFragment!=null)
					mft.detach(mHistoryFragment);
				if(mControlFragment!=null)
					mft.detach(mControlFragment);
				if(mSettingFragment!=null)
					mft.detach(mSettingFragment);
				
				//再重新添加这些子窗体，这样操作可以间接通知各个子窗体界面发生了切换，便于子窗体更新相关数据
				if(tabId.equalsIgnoreCase(EnvirFragment.TAG)){
					setupEnvirFrag();
					mCurrentTab = ENVIR_FRAG;
				}else if(tabId.equalsIgnoreCase(HistoryFragment.TAG)){	
					setupHistroyFrag();
					mCurrentTab = HISTORY_FRAG;
				}else if(tabId.equalsIgnoreCase(ControlFragment.TAG)){	
					setupControlFrag();
					mCurrentTab = CONTROL_FRAG;
				}else if(tabId.equalsIgnoreCase(SettingFragment.TAG)){	
					setupSettingFrag();
					mCurrentTab = SETTING_FRAG;
				} else {
					//界面刚启动时，根据mCurrentTab加载相关子窗体
					switch (mCurrentTab) 
					{
					case ENVIR_FRAG:
						setupEnvirFrag();
						break;
					case HISTORY_FRAG:
						setupHistroyFrag();
						break;
					case CONTROL_FRAG:
						setupControlFrag();
						break;
					case SETTING_FRAG:
						setupSettingFrag();
						break;
					default:
						setupEnvirFrag();
						break;
					}		
				}
				mft.commit();	
			}
        	
        };
        //设置初始选项卡 
        mTabHost.setCurrentTab(mCurrentTab);
        mTabHost.setOnTabChangedListener(tabChangeListener);
        initTab();
	}
	
    //创建“环境指标”子窗体
    public void setupEnvirFrag(){
    	if(mEnvirFragment==null){		
			mft.add(R.id.realTabcontent, new EnvirFragment(), EnvirFragment.TAG);						
		}else{
			mft.attach(mEnvirFragment);						
		}
    	mTitleTextView.setText(R.string.envir_target);
    	mGetSensorThread.restart();
    }
    
    //创建“历史数据查询”子窗体
    public void setupHistroyFrag(){
    	if(mHistoryFragment==null){
			mft.add(R.id.realTabcontent, new HistoryFragment(), HistoryFragment.TAG);						
		}else{
			mft.attach(mHistoryFragment);						
		}
    	mTitleTextView.setText(R.string.history_check);
    	mGetSensorThread.pause();
    }
    
    //创建“手动控制”子窗体
    public void setupControlFrag(){
    	if(mControlFragment==null){
			mft.add(R.id.realTabcontent, new ControlFragment(), ControlFragment.TAG);						
		}else{
			mft.attach(mControlFragment);						
		}
    	mTitleTextView.setText(R.string.manual_operation);
    	mGetSensorThread.pause();
    }
    
    //创建“系统设置”子窗体
    public void setupSettingFrag(){
    	if(mSettingFragment==null){
			mft.add(R.id.realTabcontent, new SettingFragment(), SettingFragment.TAG);						
		}else{
			mft.attach(mSettingFragment);	
		}
    	mTitleTextView.setText(R.string.setting);
    	mGetSensorThread.restart();
    }
    
    /**
     * 创建4个TAB view
     */
    public void createTabView()
    {
         //LinearLayout layout = (LinearLayout)mTabHost.getChildAt(0);
         TabWidget tw = (TabWidget)findViewById(android.R.id.tabs);
         
         //创建"环境指标"的tab view
         mEnvirTab = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw, false);
         TextView tvTab1 = (TextView)mEnvirTab.getChildAt(1);
         ImageView ivTab1 = (ImageView)mEnvirTab.getChildAt(0);
         ivTab1.setBackgroundResource(R.drawable.chart_icon);
         tvTab1.setText(R.string.envir_target);
         
         //创建"历史数据查询"的tab view
         mHistorytab = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw, false);
         TextView tvTab2 = (TextView)mHistorytab.getChildAt(1);
         ImageView ivTab2 = (ImageView)mHistorytab.getChildAt(0);
         ivTab2.setBackgroundResource(R.drawable.history_icon);
         tvTab2.setText(R.string.history_check);
         
         //创建"手动控制"的tab view
         mControlTab = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw, false);
         TextView tvTab3 = (TextView)mControlTab.getChildAt(1);
         ImageView ivTab3 = (ImageView)mControlTab.getChildAt(0);
         ivTab3.setBackgroundResource(R.drawable.control_icon);
         tvTab3.setText(R.string.manual_operation);
         
         //创建"系统设置"的tab view
         mSettingTab = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.tab_indicator, tw, false);
         TextView tvTab4 = (TextView)mSettingTab.getChildAt(1);
         ImageView ivTab4 = (ImageView)mSettingTab.getChildAt(0);
         ivTab4.setBackgroundResource(R.drawable.setting_icon);
         tvTab4.setText(R.string.setting);
    }
    
    /** 
     * 初始化选项卡
     * 
     * */
    public void initTab(){
    	//将"环境指标"的tab view绑定到主界面的Tab host上, 通过子窗体TAG进行关联
        TabHost.TabSpec tSpecEnvir = mTabHost.newTabSpec(EnvirFragment.TAG);
        tSpecEnvir.setIndicator(mEnvirTab);        
        tSpecEnvir.setContent(new DummyTabContent(getBaseContext()));//添加一个简单的上下文环境
        mTabHost.addTab(tSpecEnvir);
        
        //将"历史数据查询"的tab view绑定到主界面的Tab host上, 通过子窗体TAG进行关联
        TabHost.TabSpec tSpecHistory = mTabHost.newTabSpec(HistoryFragment.TAG);
        tSpecHistory.setIndicator(mHistorytab);        
        tSpecHistory.setContent(new DummyTabContent(getBaseContext()));//添加一个简单的上下文环境
        mTabHost.addTab(tSpecHistory);
        
        //将"手动控制"的tab view绑定到主界面的Tab host上, 通过子窗体TAG进行关联
        TabHost.TabSpec tSpecControl = mTabHost.newTabSpec(ControlFragment.TAG);
        tSpecControl.setIndicator(mControlTab);      
        tSpecControl.setContent(new DummyTabContent(getBaseContext()));//添加一个简单的上下文环境
        mTabHost.addTab(tSpecControl);
        
        //将"系统设置"的tab view绑定到主界面的Tab host上, 通过子窗体TAG进行关联
        TabHost.TabSpec tSpecSet = mTabHost.newTabSpec(SettingFragment.TAG);
        tSpecSet.setIndicator(mSettingTab);        
        tSpecSet.setContent(new DummyTabContent(getBaseContext()));//添加一个简单的上下文环境
        mTabHost.addTab(tSpecSet);
    }
    
    //获取到传感器数据以后，刷新环境指标子窗体界面
    @Override
    public void onGetSensor()
    {
    	FragmentManager fm =  getFragmentManager();
		if(fm != null)
		{
			EnvirFragment envirFragment = (EnvirFragment) fm.findFragmentByTag(EnvirFragment.TAG);
			//SettingFragment settingFragment = (SettingFragment) fm.findFragmentByTag(SettingFragment.TAG);
			if(envirFragment!=null){
				//刷新环境指标子窗体界面
				envirFragment.updateView();
			}
		}
    }
    
    public void setTitle(String title)
    {
    	mTitleTextView.setText(title);
    }
}
